package com.atlin.project.controller.cds;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.annotation.TrafficStatistics;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.cds.ClientCode;
import com.atlin.project.model.domain.cds.ClientFile;
import com.atlin.project.model.dto.clientFile.ClientFileAddRequest;
import com.atlin.project.model.dto.clientFile.ClientFileQueryRequest;
import com.atlin.project.model.dto.clientFile.ClientFileUpdateRequest;
import com.atlin.project.model.enums.cds.TrafficStatisticsType;
import com.atlin.project.model.vo.cds.ClientFileVO;
import com.atlin.project.service.ClientFileService;
import com.atlin.project.service.SysUserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 客户端文件
 *
 * @author atlin
 */
@RestController
@RequestMapping("/clientFile")
public class ClientFileController {

    @Resource
    private ClientFileService clientFileService;

    @Resource
    private SysUserService sysUserService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param clientFileAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addClientFile(@RequestBody ClientFileAddRequest clientFileAddRequest, HttpServletRequest request) {
        if (clientFileAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientFile clientFile = new ClientFile();
        BeanUtils.copyProperties(clientFileAddRequest, clientFile);

        clientFileService.valid(clientFile, true);
        SysUser loginUser = sysUserService.getLoginUser(request);

        // todo

        boolean result = clientFileService.save(clientFile);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newClientFileId = clientFile.getId();
        return ResultUtils.success(newClientFileId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteClientFile(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ClientFile oldclientFile = clientFileService.getById(id);
        ThrowUtils.throwIf(oldclientFile == null, ErrorCode.NULL_ERROR);


        boolean b = clientFileService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param clientFileUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateClientFile(@RequestBody ClientFileUpdateRequest clientFileUpdateRequest) {
        if (clientFileUpdateRequest == null || clientFileUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientFile clientFile = new ClientFile();
        BeanUtils.copyProperties(clientFileUpdateRequest, clientFile);

        // 参数校验
        clientFileService.valid(clientFile, false);
        long id = clientFileUpdateRequest.getId();
        // 判断是否存在
        ClientFile oldclientFile = clientFileService.getById(id);
        ThrowUtils.throwIf(oldclientFile == null, ErrorCode.NULL_ERROR);
        // todo other operation

        boolean result = clientFileService.updateById(clientFile);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<ClientFile> getClientFileById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientFile clientFile = clientFileService.getById(id);
        if (clientFile == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);

        return ResultUtils.success(clientFile);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ClientFileVO> getClientFileVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ClientFile clientFile = clientFileService.getById(id);
        if (clientFile == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        ClientFileVO clientFileVO = ClientFileVO.objToVo(clientFile);
        return ResultUtils.success(clientFileVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param clientFileQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ClientFileVO>> listClientFileVOByPage(@RequestBody ClientFileQueryRequest clientFileQueryRequest,
                                                                   HttpServletRequest request) {
        long current = clientFileQueryRequest.getCurrent();
        long size = clientFileQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ClientFile> clientFilePage = clientFileService.page(new Page<>(current, size),
                clientFileService.getQueryWrapper(clientFileQueryRequest));

        Page<ClientFileVO> clientFileVOPage = clientFileService.getClientFileVOPage(clientFilePage, request);

        return ResultUtils.success(clientFileVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param clientFileQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ClientFile>> listClientFileByPage(@RequestBody ClientFileQueryRequest clientFileQueryRequest,
                                                               HttpServletRequest request) {
        long current = clientFileQueryRequest.getCurrent();
        long size = clientFileQueryRequest.getPageSize();
        Page<ClientFile> clientFilePage = clientFileService.page(new Page<>(current, size),
                clientFileService.getQueryWrapper(clientFileQueryRequest));
        return ResultUtils.success(clientFilePage);
    }

    // endregion

    /**
     * 文件上传接口
     *
     * @param multipartFile 文件对象
     * @param clientCode    客户端标识
     * @param request       请求
     */
    @TrafficStatistics(type = TrafficStatisticsType.UPLOAD)
    @PostMapping("/upload")
    public void uploadFile(@RequestPart("file") MultipartFile multipartFile, ClientCode clientCode, HttpServletRequest request) {
        if (clientCode == null || StringUtils.isAnyBlank(clientCode.getCode(), clientCode.getFolderPath())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        clientFileService.uploadFile(multipartFile, clientCode);

    }


    /**
     * 文件下载接口
     *
     * @param clientFile 客户端文件
     * @param response   响应
     */
    @TrafficStatistics(type = TrafficStatisticsType.DOWNLOAD)
    @PostMapping("/download")
    public void downloadFile(@RequestBody ClientFile clientFile, HttpServletResponse response) {
        if (clientFile == null || clientFile.getFileMetadataId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        clientFileService.downloadFile(clientFile, response);

    }

}
